package com.example.demo.Service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.Entity.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件服务
 */
@Service
public class FileServiceImp implements FileService {

    // 文件上传存储路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${server.port:9090}")
    private String port;

    // 替换为服务器ip,前后端同设备写localhost
    @Value("${ip:192.168.78.196}")
    private String ip;

    /**
     * 文件上传
     */
    public String upload(MultipartFile file) {
        String flag;
        //路径加密
        synchronized (FileService.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
            System.out.println(fileName + "--上传成功");

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        String http = "http://" + ip + ":" + port + "/users/getFile/";
        return http + flag + "-" + fileName;
    }


    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */
    public void avatarPath(String flag, HttpServletResponse response) {
        OutputStream os;
                try {
                    if (StrUtil.isNotEmpty(flag)) {
                        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                        response.setContentType("application/octet-stream");
                        byte[] bytes = FileUtil.readBytes(filePath + flag);
                        os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * 删除文件
     */
    public void delFile(String flag) {
        List<String> fileNames = FileUtil.listFileNames(filePath);
        FileUtil.del(filePath + flag);
        System.out.println("删除文件" + flag + "成功");
    }
}
